package me.duzhi.blog.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.render.Render;
import io.jpress.core.JBaseController;
import io.jpress.interceptor.InterUtils;
import io.jpress.model.Content;
import io.jpress.model.Metadata;
import io.jpress.model.User;
import io.jpress.model.query.ContentQuery;
import io.jpress.model.query.MetaDataQuery;
import io.jpress.router.RouterMapping;
import io.jpress.utils.StringUtils;
import me.duzhi.blog.function.Functions;
import me.duzhi.blog.searcher.LuceneSearcher;
import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ashang.peng@aliyun.com
 * @date 十二月 09, 2016
 */
@RouterMapping(url = "/to_all")
public class ImageController extends JBaseController {
    public static final String imgUrl = "img1.duzhi.me";
    public static final String localimgDir = "";
    public static final Map<String, Integer> finalStar = new HashMap();

    static {
        finalStar.put("starthree", 3);
        finalStar.put("startwo", 2);
        finalStar.put("starone", 1);
        finalStar.put("starfive", 5);
        finalStar.put("starfour", 4);
    }


    public void  url(){
        String type =  getPara(0);
        BigInteger pid = getParaToBigInteger(1);
        Content content = ContentQuery.me().findById(pid);
        String source = content.getMetadata("source");
        if(StringUtils.isNotBlank(source)){
            redirect(source,true);
        }

    }

    public void ip(){
        System.out.println("header params");
        Enumeration hnames=getRequest().getHeaderNames();
        for (Enumeration e = hnames ; e.hasMoreElements() ;) {
            String thisName=e.nextElement().toString();
            String thisValue=getRequest().getHeader(thisName);
            System.out.println(thisName+"-------"+thisValue);
        }
        System.out.println("request params:");
        Enumeration rnames=getRequest().getParameterNames();
        for (Enumeration e = rnames ; e.hasMoreElements() ;) {
            String thisName=e.nextElement().toString();
            String thisValue=getRequest().getParameter(thisName);
            System.out.println(thisName+"-------"+thisValue);
        }
        renderAjaxResultForError();
    }

    @Before(POST.class)
    public void ajax() {
        String action = getPara("action");
        if ("rating".equals(action)) {
            int pid = getParaToInt("pid");
            BigInteger id = BigInteger.valueOf(pid);
            String sid = getPara("sid");
            Functions.setMetaData(id, sid);
        }
        else if("updateViewCount".equals(action)){
            int pid = getParaToInt("pid");
          //  Functions.updateViewCount(pid);
        }else if("like".equals(action)){
            int pid = getParaToInt("pid");
            User user = InterUtils.tryToGetUser(this);
            Functions.like(BigInteger.valueOf(pid),user);
        }

        renderAjaxResult("ok", 0);
    }

    private void setMetaData(BigInteger id, String sid) {
        String ratesdes = "ratesdes";//描述
        String ratingCount= "ratingCount";//总数
        String ratingValue= "ratingValue";//平均值
        Metadata metadata = MetaDataQuery.me().findByTypeAndIdAndKey("content", id, "ratingValue");
        float _ratingValue = new Float(metadata.getMetaValue());
        _ratingValue = (_ratingValue + finalStar.get(sid)) / 2;
        DecimalFormat fnum   =   new   DecimalFormat("##0");
        String _ratesdes = fnum.format(_ratingValue);

        if (metadata == null) {
            metadata = new Metadata();
            metadata.setMetaKey("ratingValue");
            metadata.setMetaValue(String.valueOf(finalStar.get(sid)));
        } else {
            metadata.setMetaValue(String.valueOf(_ratingValue));
        }
    }

    public void index() throws IOException {
        try {
            getResponse().setContentType("image/jpeg");
            String surl = getPara("src");
            int width = getParaToInt("width");
            int height = getParaToInt("height");
            render(new Render() {
                @Override
                public void render() {
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                    response.setDateHeader("Expires", 0);
                    response.setContentType("image/jpeg");
                    try {
                        URL url1 = new URL(surl);
                        String fileName = null;
                        String traceImageName = null;
                        if (imgUrl.equals(url1.getHost())) {
                            fileName = surl.substring(surl.lastIndexOf("/"), surl.lastIndexOf("."));
                            if (fileName.indexOf("_") <= -1) {
                                traceImageName = fileName + "_" + width + "*" + height;
                            }
                        }
                        String imgPath = url1.getPath();
                        String _surl = surl.replaceAll(fileName, traceImageName);
                        imgPath = imgPath.replaceAll(fileName, traceImageName);
                        File imgFile = new File(localimgDir + imgPath);
                        if (imgFile.exists()) {
                            Thumbnails.of(imgFile).toOutputStream(response.getOutputStream());
                        } else {
                            // / Thumbnails.of(url1).forceSize(wi)
                            Thumbnails.of(url1).forceSize(width, height).toOutputStream(response.getOutputStream());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reloadLucene(){
        String createIndexSearcher = getPara("createIndexSearcher");
        if("10bf8b728e72ae7c496512ef15eff9b08adb7d118eaa32e3c3a01c38f4c4dc69".equals(createIndexSearcher)){
            LuceneSearcher.reloadIndex();
        }
        renderAjaxResultForSuccess();
    }

}
